package com.example.demo.heartbeat;

import com.example.demo.util.SpringContextUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.net.InetAddress;
import java.util.Date;
import java.util.Map;

/**
 * Title: HeartBeatClientHandler
 * Description: 客户端业务逻辑实现
 * Version:1.0.0
 *
 * @author kh
 * @date 2021-08-10 16:39:25
 */
@Slf4j
public class HeartBeatClientHandler extends SimpleChannelInboundHandler<HeartBeat> {

    /**
     * 空闲次数
     */
    private int idle_count = 1;

    /**
     * 发送次数
     */
    private int count = 1;

    /**
     * 循环次数
     */
    private int fcount = 1;


    /**
     * 建立连接时
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("建立连接时：" + new Date());
        ctx.fireChannelActive();
    }

    /**
     * 关闭连接时
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("关闭连接时：" + new Date());
        final EventLoop eventLoop = ctx.channel().eventLoop();
        HeartBeatClient heartBeatClient = SpringContextUtil.getBean(HeartBeatClient.class);
        heartBeatClient.doConnect(new Bootstrap(), eventLoop);
        super.channelInactive(ctx);
    }

    /**
     * 心跳请求处理
     *
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj;
            //如果写通道处于空闲状态,就发送心跳命令
            if (IdleState.WRITER_IDLE.equals(event.state())) {
                //向服务端发送消息
                InetAddress addr = InetAddress.getLocalHost();
                String hostName = addr.getHostName();
                String hostAddress = addr.getHostAddress();
                HeartBeat heartBeat = new HeartBeat();
                heartBeat.setBusinessId(123L);
                heartBeat.setHostName(hostName);
                heartBeat.setHostAddress(hostAddress);
                heartBeat.setClientVersion(getVersion());
                log.info("===========心跳服务版本：" + heartBeat);

                ctx.channel().writeAndFlush(heartBeat).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HeartBeat heartBeat) throws Exception {

    }

//    /**
//     * 业务逻辑处理
//     */
//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//
//    }

//    @Override
//    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HeartBeat customProtocol)
//            throws Exception {
//        System.out.println("第"+count+"次"+",客户端接受的消息:content:"+customProtocol.getHostName()
//                +" id:"+customProtocol.getBusinessId());
//        count++;
//    }


    public String getVersion() {
        YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean();
        //可以加载多个yml文件
        yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
        //通过getObject()方法获取Map对象
        Map<String, Object> map = yamlMapFactoryBean.getObject();
        return String.valueOf(map.get("version") == null ? "" : map.get("version"));
    }


}
